package top.milkbox.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.milkbox.domain.User;
import top.milkbox.info.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler) throws Exception {
        if (isUserLogin(request.getCookies())) {
            log.debug("用户已登录，拦截器通过");
            return true; // 通过
        } else {
            log.debug("用户未登录，拦截请求：" + request.getRequestURL());

            response.setContentType("application/json;charset=utf-8");
            objectMapper.writeValue(response.getWriter(),
                    new R(false, null, "请您先登录"));
            return false; // 拦截
        }
    }


}
